<?php

namespace App\Orchid\Layouts\Category;

use App\Models\Category;
use Orchid\Screen\TD;
use Orchid\Screen\Actions\Link;
use Orchid\Screen\Layouts\Table;

class CategoryListLayout extends Table
{
    /**
     * Data source.
     *
     * The name of the key to fetch it from the query.
     * The results of which will be elements of the table.
     *
     * @var string
     */
    protected $target = 'categories';

    /**
     * Get the table cells to be displayed.
     *
     * @return TD[]
     */
    protected function columns(): iterable
    {
        return [
            TD::make('name', '分类名称')
                ->sort()
                ->filter(TD::FILTER_TEXT)
                ->render(function (Category $category) {
                    return Link::make($category->name)
                        ->route('platform.categories.edit', $category);
                }),
                
            TD::make('slug', 'Slug')
                ->sort(),
                
            TD::make('parent.name', '父分类')
                ->render(function (Category $category) {
                    return $category->parent ? $category->parent->name : '-';
                }),
                
            TD::make('posts_count', '文章数量')
                ->render(function (Category $category) {
                    return $category->posts()->count();
                }),
                
            TD::make('description', '描述')
                ->render(function (Category $category) {
                    $description = $category->description;
                    if (strlen($description) > 50) {
                        return substr($description, 0, 50) . '...';
                    }
                    return $description ?: '-';
                }),
                
            TD::make('created_at', '创建时间')
                ->sort()
                ->render(function (Category $category) {
                    return $category->created_at->format('Y-m-d H:i');
                }),
                
            TD::make('操作')
                ->align(TD::ALIGN_CENTER)
                ->width('150px')
                ->render(function (Category $category) {
                    return Link::make('编辑')
                        ->icon('pencil')
                        ->route('platform.categories.edit', $category);
                }),
        ];
    }
}